<template>
  <!--页面搭建-杜思成-->
  <layout-card
    v-model="search"
    :filters="exampleOptions"
    headline="信息列表"
    headtitle="数据筛选"
    :hasButton="true"
    @search-change="getData"
    @search-reset="searchReset"
  >
    <template #action>
      <el-button
        type="primary"
        @click="handleExport"
        :disabled="data?.data?.list.length === 0"
        >导出</el-button
      >
      <el-button type="primary" @click="handleCreate()">新增</el-button>
    </template>
    <table-common
      stripe="true"
      :columns="exampleColumns"
      :loading="loading"
      :pagination="pager"
      :table-data="data?.data?.list"
      size="large"
      @current-change="changeCurrent"
      @size-change="changePageSize"
      @sort-change="sortChange"
    >
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleEdit(row)" link type="primary"
          >编辑</el-button
        >
        <el-popconfirm
          title="是否删除?"
          confirmButtonText="确定"
          cancelButtonText="取消"
          @confirm="() => handleDelete(row)"
        >
          <template #reference>
            <el-button class="link-btn" link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>
  <Edit
    :visible="centerDialogVisible"
    :info="info"
    :title="title"
    :filters="typeInfp"
    :organInfo="organInfo"
    :key="timer"
    :disabled="disabled"
    :close-on-click-modal="false"
    @cancel="handleCancel"
    @ok="handleOk"
  />
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
// 7-18修改LayoutCard 页面，hasButton参数为false时显示为弹窗样式，为true时显示为搜索栏样式
import LayoutCard from "@/components/LayoutCard/index.vue";
import TableCommon from "@/components/TableCommon/index.vue";
import { exampleColumns } from "@/views/rep/problem/config/columns";
import { exampleOptions } from "@/views/rep/problem/config/filters";
import {
  reqPage,
  reqtypeList,
  downloadFile,
  addPro,
  updatePro,
  deletePro,
} from "@/api/rep/problem";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import Edit from "./eidt.vue";
const store = useStore();
const userInfo = store.state.user.userInfo; // 登录用户数据

const organTree = store.state.user.organTree;
// 时间戳，用于确保弹窗页面能加载不同的界面
const timer = ref();
const data = ref({}); // table数据
const loading = ref(false);
// 是否只读
const disabled = ref(false);
const info = ref(); // 当前行数据
const typeInfp = ref([]); // 弹出框输入框格式
const organInfo = ref([]); // 下拉框选项
// 新增弹窗是否打开
const centerDialogVisible = ref(false);
/**
 * @functionName 编辑框
 * @param row
 * @description
 * @author 陈振兵
 * @date 2023-07-26 17:31:15
 * @version V1.0.0
 * @return
 */
const handleEdit = (row = null) => {
  timer.value = new Date().getTime();
  centerDialogVisible.value = true;
  disabled.value = true;
  info.value = row;
};
/**
 * @functionName 弹出框
 * @param row
 * @description
 * @author 陈振兵
 * @date 2023-07-26 17:32:02
 * @version V1.0.0
 * @return
 */
const handleCreate = (row = null) => {
  timer.value = new Date().getTime();
  centerDialogVisible.value = true;
  disabled.value = false;
  info.value = row;
};

/**
 * 弹窗点击取消
 */
const handleCancel = () => {
  centerDialogVisible.value = false;
  info.value = null;
};
/**
 * @functionName 新增、编辑功能
 * @param {any} form 表单的内容
 * @param {any} info 当前行的内容
 * @param {any} oraganName 使用者的名字
 * @description
 * @author 陈振兵
 * @date 2023-07-26 17:32:41
 * @version V1.0.0
 * @return
 */
const handleOk = async (form: any, info: any, oraganName: any) => {
  if (info) {
    // TODO:编辑
    const data = {
      problemId: info.problemId,
      typeId: info.typeId,
      problemType: form.proType,
      owner: {
        id: info.owner.id,
        name: info.owner.name,
      },
      mender: {
        userId: userInfo.userId,
        name: userInfo.name,
        organId: info.creator.organId,
        organName: info.creator.organName,
      },
    };
    const res: any = await updatePro(data);
    if (res.code === "1") {
      ElMessage.success("编辑成功！");
      centerDialogVisible.value = false;
      getData();
    } else {
      ElMessage.error("数据重复，编辑失败！");
      centerDialogVisible.value = true;
    }
  } else {
    // TODO：新增
    const data = {
      typeId: form.DeviceType,
      problemType: form.proType,
      owner: {
        id: form.oragan,
        name: oraganName,
      },
      creator: {
        userId: userInfo.userId,
        name: userInfo.name,
        organId: userInfo.organId,
        organName: userInfo.organName,
      },
    };
    addPro(data)
      .then((res: any) => {
        if (res.code === "1") {
          ElMessage.success("新增成功！");
          centerDialogVisible.value = false;
          getData();
        } else {
          ElMessage.error("数据重复，新增失败！");
          centerDialogVisible.value = true;
        }
      })
      .catch((err: any) => {
        console.log(err);
      });

    centerDialogVisible.value = false;
  }
};
/**
 * @functionName 删除功能
 * @param {any} row 当前行的内容
 * @description
 * @author 陈振兵
 * @date 2023-07-26 17:35:43
 * @version V1.0.0
 * @return
 */
const handleDelete = async (row: any) => {
  const data = {
    problemId: row.problemId,
    mender: {
      id: userInfo.userId,
      name: userInfo.userName,
      organId: userInfo.organId,
      organName: userInfo.organName,
    },
  };
  const res: any = await deletePro(data);
  if (res.code === "1") {
    ElMessage.success("删除成功！");
  } else {
    ElMessage.success("删除失败！");
  }
  getData();
};

// 分页数据
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageCount: 0,
});
const search = ref({});

// 查询条件
const param = ref({
  typeId: "",
  problemType: "",
  timeStart: "",
  timeEnd: "",
  order: {
    column: "createTime",
    method: "desc",
  },
});

/**
 * @functionName getSearchData
 * @param {any} searchData 查询参数
 * @description 查询参数格式封装
 * @author 蒋好东
 * @date 2023-07-26 17:36:24
 * @version V1.0.0
 * @return 查询数据
 */
const getSearchData = (searchData: any) => {
  return {
    typeId: searchData.typeId === undefined ? undefined : searchData.typeId,
    problemType:
      searchData.problemType === undefined ? undefined : searchData.problemType,
    timeStart: Array.isArray(searchData?.date1)
      ? searchData?.date1?.length === 0
        ? undefined
        : searchData?.date1[0]
      : undefined,
    timeEnd: Array.isArray(searchData?.date1)
      ? searchData?.date1?.length === 0
        ? undefined
        : searchData?.date1[1]
      : undefined,
    owner: searchData.tree === undefined ? undefined : { id: searchData.tree },
    order: {
      column: "createTime",
      method: "desc",
    },
  };
};

/**
 * @functionName getData
 * @param
 * @description 分页数据查询
 * @author 彭庆楠
 * @date 2023-07-26 17:36:24
 * @version V1.0.0
 * @return 数据展示
 */
const getData = async () => {
  loading.value = true;
  const params = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {
      ...getSearchData(search.value),
    },
  };

  await reqPage(params).then((resp) => {
    data.value = resp;
    pager.total = resp.data.total;
    pager.pageCount =
      Math.ceil(pager.total / pager.pageSize) === 0
        ? 1
        : Math.ceil(pager.total / pager.pageSize);

    loading.value = false;
  });
};
/**
 * @functionName 清空方法
 * @param {any} data
 * @description
 * @author 彭庆楠
 * @date 2023-07-26 17:39:06
 * @version V1.0.0
 * @return
 */
const searchReset = (data: any) => {
  search.value = data;
  pager.currentPage = 1;
  pager.pageSize = 10;
  getData();
};
/**
 * @functionName 排序事件
 * @param {any} data 当前列的字段名和升降序
 * @description
 * @author 彭庆楠
 * @date 2023-07-26 17:42:56
 * @version V1.0.0
 * @return
 */
const sortChange = (data: any) => {
  const method = data.order === "ascending" ? "asc" : "desc";
  param.value.order.method = method;
  getData();
};
/**
 * @functionName 获取树形结构数据
 * @description 该方法用来解析树形对象成三维数组
 * @author 彭庆楠
 * @date 2023-07-26 17:44:08
 * @version V1.0.0
 * @return
 */
const typelist = async () => {
  const param = {
    owner: {
      organId: userInfo.organId,
    },
  };
  if (userInfo.organName === "TOC") {
    param.owner.organId = "TOC";
  }
  await reqtypeList(param).then((resp) => {
    resp.data.forEach((e: any) => {
      const type = {
        value: e.typeId,
        label: e.typeName,
        children: [] as any,
      };
      if (e.children) {
        e.children.forEach((c: any) => {
          const ctype = {
            value: c.typeId,
            label: c.typeName,
          };
          type.children.push(ctype);
        });
      }
      getData();
      exampleOptions.value[0].inputProps.data.push(type);
    });
    typeInfp.value = exampleOptions.value[0].inputProps.data;
  });
};
// 树形所属单位
const organlist = async () => {
  organTree.forEach((e: any) => {
    const type = {
      value: e.data.organId,
      label: e.data.name,
      children: [] as any,
    };
    if (e.children) {
      e.children.forEach((c: any) => {
        const ctype = {
          value: c.data.organId,
          label: c.data.name,
          children: [] as any,
        };
        if (c.children) {
          c.children.forEach((cc: any) => {
            const cctype = {
              value: cc.data.organId,
              label: cc.data.name,
            };
            ctype.children.push(cctype);
          });
        }
        type.children.push(ctype);
      });
    }
    exampleOptions.value[2].inputProps.data.length = 0;

    exampleOptions.value[2].inputProps.data.push(type);
  });
  organInfo.value = exampleOptions.value[2].inputProps.data;
};
// 当前页
const changeCurrent = (currentPage: number) => {
  pager.currentPage = currentPage;
  getData();
};
// 分页
const changePageSize = (pageSize: number) => {
  pager.pageSize = pageSize;
  getData();
};
/**
 * @functionName 导出功能
 * @author 蒋浩东
 * @date 2023-07-26 17:45:27
 * @version V1.0.0
 */
const handleExport = () => {
  const download = getSearchData(search.value);
  const date = new Date();
  const dateNumber =
    date.getFullYear() * 1e4 + (date.getMonth() + 1) * 1e2 + date.getDate();
  downloadFile(download).then((res: any) => {
    const fileName = "报修问题管理" + dateNumber + ".xlsx"; // 自定义文件名
    const blob = new Blob([res], {
      type: "application/vnd.ms-excel;charset=utf-8", // 文件格式
    });
    const link = document.createElement("a"); // 创建下载链接
    link.href = URL.createObjectURL(blob);
    link.download = `${fileName}`;
    link.click();
    URL.revokeObjectURL(link.href);
    link.remove();
  });
};

onMounted(() => {
  getData();
  typelist();
  organlist();
});
</script>
